package clas.ac.cn.common.advice;


import clas.ac.cn.common.exception.IException;
import clas.ac.cn.common.exception.NotFoundException;
import clas.ac.cn.common.vo.CommonResponse;

import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(value = IException.class)
    @ResponseBody
    public CommonResponse<String> handlerException(HttpServletRequest request, IException e) {
        log.error("IException拦截:e=>" + e.getMessage());
        return new CommonResponse<>(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    public CommonResponse<String> exceptionHandler(HttpServletRequest request, Exception ex) {
        log.error("数据转换拦截:e=>" + ex.getMessage());
        return new CommonResponse<>(-1, ex.getMessage());
    }
    @ExceptionHandler(value = NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public CommonResponse<String> handlerNotFoundException(HttpServletRequest request, NotFoundException e) {
        log.error("Exception拦截:url=>" + request.getRequestURI() + "e=>" + e.getMessage() );

        return new CommonResponse<>(e);
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public CommonResponse<String> bootNotFoundException(HttpServletRequest request, NoHandlerFoundException e) {
        log.error("Exception拦截:url=>" + request.getRequestURI() + "e=>" + e.getMessage() );

        return new CommonResponse<>(new NotFoundException(e.getMessage(), HttpStatus.NOT_FOUND.value()));
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponse<String> handlerException(HttpServletRequest request, Exception e) {
        log.error("Exception拦截:url=>" + request.getRequestURI() + "e=>" + e.getMessage());

        return new CommonResponse<>(new IException(e.getMessage()));
    }
}
